import React from 'react'
import io from 'socket.io-client'
import {connect} from 'react-redux'

import './socket-demo.css'




const url='ws://localhost:9093'

const socket = io(url);
@connect(
  state=>state,
  {}
)
class SocketDemo extends React.Component{
  constructor(props) {
    super(props);
    this.state={
      message:'',
      user:this.props.User.user,
      messages:[]
    }
    this.send=this.send.bind(this)
    this.login=this.login.bind(this)
    this.onKeyDown=this.onKeyDown.bind(this)
  }

  componentDidMount() {
    //输入欢迎信息
    this.login()
    //增加回车事件
    document.addEventListener("keydown", this.onKeyDown)
    //socket.io连接后台
    io(url).on('connect', ()=>{
      console.log('connect');

      socket.on('messages', data => {
        //返回用户列表
        this.setState({
          messages:[...this.state.messages,data]
        })
        if(this.refs.showDiv){
          this.refs.showDiv.scrollTop=20000
        }

      });
    });
  }
  componentWillUnmount() {
    //断开socket io连接
    io(url).on('disconnect', function(){
      console.log('disconntect');
    });

    document.removeEventListener("keydown", this.onKeyDown)
  }

  //鼠标回车事件
  onKeyDown(e){
    switch (e.keyCode) {
      case 13:
        this.send();
        return;
      default:
        return;
    }
  }

  //向后台发送信息
  send(){
    let {user,message}=this.state;
    // console.log(this.refs.showDiv);

    socket.emit('messages', {user,message});
    this.setState({
      message:''
    })
  }

  login(){
    let user=this.props.User.user;
    const obj={user:'作者',message:`欢迎${user}来到聊天室`}
    if(user.trim()!==''){
      this.setState({
        user:user,
        messages:[obj]
      })
    }
  }

  //赋值state
  handleChange(title,target){
    this.setState({
      [title]:target.target.value
    })
  }
  render() {
    let cn='showInfo'
    return (
      <div>
      <div className='talkDiv'>
      <div className='operatingDiv'>
      <input
    type='text'
    placeholder='请在此输入聊天信息'
    onChange={v=>this.handleChange('message',v)}
    value={this.state.message}
    />
    <button onClick={this.send}>发送链接</button>
      </div>
      <div ref='showDiv' className='showDiv'>
      {

        this.state.messages.map((v,index)=>{
          if(index===0){
            cn='titleInfo'
          }else{
            cn='showInfo'
          }
          return (
            <div className={cn} key={index}>
            <span>{v.user}:</span>
          <span>{v.message}</span>
          </div>
        )
        })
      }
      </div>
      </div>

      </div>
  );
  }
}

export default SocketDemo;
